package com.lineage.server.timecontroller.server;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.serverpackets.S_PacketBoxGame;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerUseMapTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(ServerUseMapTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public static final Map<L1PcInstance, Integer> MAP = new ConcurrentHashMap<>();
  
  public void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
  
  public static void put(L1PcInstance pc, int time) {
    MAP.put(pc, new Integer(time));
  }
  
  public void run() {
    try {
      if (!MAP.isEmpty()) {
        Iterator<L1PcInstance> iterator = MAP.keySet().iterator();
        while (iterator.hasNext()) {
          L1PcInstance key = iterator.next();
          Integer value = MAP.get(key);
          if (key.getMapId() != key.get_other().get_usemap()) {
            teleport(key);
            return;
          } 
          value = Integer.valueOf(value.intValue() - 1);
          if (value.intValue() <= 6) {
            teleport(key);
            Thread.sleep(1L);
            continue;
          } 
          if (value.intValue() <= 4) {
            teleport(key);
            Thread.sleep(1L);
            continue;
          } 
          if (value.intValue() <= 2) {
            teleport(key);
            Thread.sleep(1L);
            continue;
          } 
          if (value.intValue() == 0) {
            teleport(key);
            Thread.sleep(1L);
            continue;
          } 
          if (value.intValue() % 1 != 0)
            continue; 
          key.get_other().set_usemapTime(value.intValue());
          put(key, value.intValue());
          key.sendPackets((ServerBasePacket)new S_PacketBoxGame(71, key.get_other().get_usemapTime()));
        } 
      } 
    } catch (Exception e) {
      _log.error("短时间计时地图时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      ServerUseMapTimer useMapTimer = new ServerUseMapTimer();
      useMapTimer.start();
    } 
  }
  
  public static void teleport(L1PcInstance tgpc) {
    MAP.remove(tgpc);
    if (World.get().getPlayer(tgpc.getName()) == null)
      return; 
    if (tgpc.getMapId() == tgpc.get_other().get_usemap())
      L1Teleport.teleport(tgpc, 33430, 32808, (short)4, 5, true); 
    tgpc.get_other().set_usemapTime(0);
    tgpc.get_other().set_usemap(-1);
    tgpc.sendPackets((ServerBasePacket)new S_PacketBoxGame(72));
  }
}
